import 'package:dmz/request/apis.dart';
import 'package:dmz/request/config.dart';
import 'package:dmz/request/request_client.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_oss_aliyun/flutter_oss_aliyun.dart';
import 'package:intl/intl.dart';

class OssUtils {
  static initOss() async {
    var value = await RequestClient().get<Map>(APIS.getOssToken);
    if (value != null) {
      Client.init(
          ossEndpoint: "oss-cn-shenzhen.aliyuncs.com",
          bucketName: value['bucket'],
          authGetter: () => _authGetter(value));
    }
  }

  static Auth _authGetter(Map data) {
    DateTime now = DateTime.now().toUtc();
    String formattedDate = DateFormat('yyyy-MM-ddTHH:mm:ss\'Z\'').format(now);
    debugPrint('initOss 初始化数据2 --- $data');
    return Auth(
      accessKey: data["access_key"],
      accessSecret: data['access_secret'],
      expire: formattedDate,
      secureToken: data['security_token'],
    );
  }

  static Future<String?> updataImages(List<int> bytes) async {
    DateTime now = DateTime.now().toUtc();
    String formattedDate = DateFormat('yyyy-MM-ddTHH:mm:ss').format(now);
    String imagePaht = 'smartemc/${formattedDate}_user.png';
    var result = await Client().putObject(bytes, imagePaht,
        option: PutRequestOption(
          onSendProgress: (count, total) {
            if (kDebugMode) {
              print("send: count = $count, and total = $total");
            }
          },
          onReceiveProgress: (count, total) {
            if (kDebugMode) {
              print("receive: count = $count, and total = $total");
            }
          },
          override: false,
          aclModel: AclMode.private,
          storageType: StorageType.standard,
          headers: {"cache-control": "no-cache"},
        ));
    debugPrint('Oss 上传结果 --- ${result.statusCode}');
    if (result.statusCode == 200) {
      return imagePaht;
    } else {
      return null;
    }
  }

  ///多张图片上传
  static updataMoreImages(List<List<int>> bytes) async {
    DateTime now = DateTime.now().toUtc();
    String formattedDate = DateFormat('yyyy-MM-ddTHH:mm:ss').format(now);
    debugPrint('Oss 上传结果 ---  000');
    var results = await Client().putObjects(List.generate(
        bytes.length,
        (index) => AssetEntity(
            filename: 'smartemc/${formattedDate}_repair$index.png',
            bytes: bytes[index])));
    List<String> result = [];
    for (var element in results) {
      debugPrint(
          '图片上传 ---- ${element.statusCode} -- ${element.requestOptions.path}');
      if (element.statusCode == 200) {
        result
            .add(element.requestOptions.path.replaceAll(RequestConfig.oss, ''));
      }
    }
    return result;
  }
}
